<template>
  <div>
    <el-tree
      ref="tree"
      :data="list"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      :props="{label: 'name'}"
      show-checkbox
      check-strictly
    />
    <div style="text-align: center">
      <el-button size="mini" @click="cencel">取消</el-button>
      <el-button size="mini" type="primary" @click="hSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getTree1 } from '@/utils/index'
import { getRoleDetailAPI, assignPermAPI } from '@/api/setting'
import {
  getPermissionListAPI
} from '@/api/permission'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 用户点击取消
    cencel() {
      this.$emit('success')
    },
    // 点击确定
    hSubmit() {
      this.assignPerm()
    },
    // 获取权限列表
    async getPermissionList() {
      try {
        const res = await getPermissionListAPI()
        // console.log('', res)
        // 保存数据
        this.list = getTree1(res.data)
        this.validList = res.data
      } catch (err) {
        console.log('', err)
      }
    },
    // 数据回填
    async getRoleDetail() {
      try {
        const { data: res } = await getRoleDetailAPI(this.roleId)
        // console.log('', res)
        // 保存数据
        // el-tree组件的API：setCheckedKeys()设置目前勾选的节点,参数接收勾选节点数据的数组
        this.$refs.tree.setCheckedKeys(res.permIds)
      } catch (err) {
        console.log('', err)
      }
    },
    // 保存权限分配
    async assignPerm() {
      const permIds = this.$refs.tree.getCheckedKeys()
      try {
        await assignPermAPI({ id: this.roleId, permIds: permIds })
        // 保存数据
        this.$emit('success')
      } catch (err) {
        console.log('', err)
      }
    }
  }
}
</script>

<style>

</style>
